<template>
  <view class="page page-coupon-form ui-form-basic">
    <page-header :showPlaceHolder="false" :customTitle="customTitle"></page-header>
    <fui-form ref="formRef" :model="form" class="form-wrapper grey" labelWidth="200" labelSize="28" labelWeight="bold" :top="store.getters.topHeight">
      <view class="form-block">
        <fui-form-item label="优惠券名称" prop="name" left="0" marginTop="14" :padding="['16rpx', 0]">
          <fui-input size="28" maxlength="15" :padding="[0]" :borderBottom="false" placeholder="请输入优惠券名称" v-model="form.name" :disabled="disabledEdit" :color="formColor"></fui-input>
        </fui-form-item>
        <fui-form-item :bottomBorder="false" label="推广人群" prop="targetCrowd"
          labelWeight="600" :left="0" :padding="['16rpx', 0]" labelWidth="200" class="textarea-box" labelSize="28">
          <view class="cycle-box" :style="{opacity: disabledEdit ? 0.8 : 1}">
            <view class="cycle" :class="{'cycle-active': form.targetCrowd == item.code}"
              v-for="item in COUPON_USER_TYPE" :key="item.code" @click="handleChangeUserType(item.code)">
              <image v-if="form.targetCrowd == item.code" class="cycleimg"
                src="../../static/images/cycleimg.png" mode=""></image>
              {{item.name}}
            </view>
          </view>
        </fui-form-item>
        <fui-form-item :bottomBorder="false" label="使用范围" prop="productScope"
          labelWeight="600" :left="0" :padding="['16rpx', 0]" labelWidth="200" class="textarea-box" labelSize="28">
          <view class="cycle-box" :style="{opacity: disabledEdit ? 0.8 : 1}">
            <view class="cycle" :class="{'cycle-active': form.productScope == item.code}"
              v-for="item in filterGoodsRange" :key="item.code" @click="handleChangeGoodsRange(item.code)">
              <image v-if="form.productScope == item.code" class="cycleimg"
                src="../../static/images/cycleimg.png" mode=""></image>
              {{item.name}}
            </view>
          </view>
        </fui-form-item>
        <view class="form-block-title" v-if="form.productScope === 32">
          已选品类<fui-text :text="`(${checkedCategoryIds.length})`" :padding="[0, '10rpx']" size="24" fontWeight="bold" color="var(--fui-color-primary)"></fui-text>
          <view class="form-block-tools">
            <fui-text :text="disabledEdit ? '查看品类' : '选择品类'" size="24" color="var(--fui-color-primary)" @click="onShowCategoryPicker"></fui-text>
          </view>
        </view>
        <view class="form-block-title" v-if="form.productScope === 33">
          已选供应商
          <fui-text v-if="checkedSupplierIds.indexOf('-1') > -1" text="(全部直供)" :padding="[0, '10rpx']" size="24" fontWeight="bold" color="var(--fui-color-primary)"></fui-text>
          <fui-text v-else-if="checkedSupplierIds.indexOf('-2') > -1" text="(全部自营)" :padding="[0, '10rpx']" size="24" fontWeight="bold" color="var(--fui-color-primary)"></fui-text>
          <fui-text v-else :text="`(${checkedSupplierIds.length})`" :padding="[0, '10rpx']" size="24" fontWeight="bold" color="var(--fui-color-primary)"></fui-text>
          <view class="form-block-tools">
            <fui-text :text="disabledEdit ? '查看供应商' : '选择供应商'" size="24" color="var(--fui-color-primary)" @click="handleManageSullier"></fui-text>
          </view>
        </view>
        <view class="form-block-title" v-if="form.productScope === 72">
          已选商品<fui-text :text="`(${checkedGoodsIds.length})`" :padding="[0, '10rpx']" size="24" fontWeight="bold" color="var(--fui-color-primary)"></fui-text>
          <view class="form-block-tools">
            <fui-text :text="disabledEdit ? '查看商品' : '选择商品'" size="24" color="var(--fui-color-primary)" @click="handleManageGoods"></fui-text>
          </view>
        </view>
      </view>
      <view class="form-block">
        <fui-form-item label="领取起始时间" prop="startReceiveTimeText" left="0" marginTop="14" :padding="['16rpx', 0]" arrow @click="handleShowDatePicker('startReceiveTimeText')">
          <fui-input size="28" :padding="[0]" :borderBottom="false" placeholder="请选择领取起始时间" v-model="form.startReceiveTimeText" disabled :color="formColor"></fui-input>
        </fui-form-item>
        <fui-form-item label="领取截止时间" prop="startReceiveTimeText" left="0" marginTop="14" :padding="['16rpx', 0]" arrow @click="handleShowDatePicker('endReceiveTimeText')">
          <fui-input size="28" :padding="[0]" :borderBottom="false" placeholder="请选择领取截止时间" v-model="form.endReceiveTimeText" disabled :color="formColor"></fui-input>
        </fui-form-item>
        <fui-form-item label="使用起始时间" prop="useStartTimeText" left="0" marginTop="14" :padding="['16rpx', 0]" arrow @click="handleShowDatePicker('useStartTimeText')">
          <fui-input size="28" :padding="[0]" :borderBottom="false" placeholder="请选择使用起始时间" v-model="form.useStartTimeText" disabled :color="formColor"></fui-input>
        </fui-form-item>
        <fui-form-item label="使用截止时间" prop="useEndTimeText" left="0" marginTop="14" marginBottom="32" :padding="['16rpx', 0]" arrow @click="handleShowDatePicker('useEndTimeText')">
          <fui-input size="28" :padding="[0]" :borderBottom="false" placeholder="请选择使用截止时间" v-model="form.useEndTimeText" disabled :color="formColor"></fui-input>
        </fui-form-item>
        <view class="form-block-title">优惠信息</view>
        <view class="discount-wrapper">
          <fui-text text="满" size="24"></fui-text>
          <fui-form-item label="" prop="startNum" left="0" :padding="['16rpx', 0]">
            <fui-input v-model="form.startNum" type="number" placeholder="请输入金额" backgroundColor="transparent" size="24" :padding="[0]" :borderBottom="false" :maxlength="20" :disabled="disabledEdit" :color="formColor" @input="onChangeStartNum"></fui-input>
          </fui-form-item>
          <fui-text text="减" size="24"></fui-text>
          <fui-form-item label="" prop="discountNum" left="0" :padding="['16rpx', 0]">
            <fui-input v-model="form.discountNum" type="digit" placeholder="请输入金额" backgroundColor="transparent" size="24" :padding="[0]" :borderBottom="false" :maxlength="20" :disabled="disabledEdit" :color="formColor" @input="onChangeDiscountNum"></fui-input>
          </fui-form-item>
        </view>
      </view>
      <view class="form-block">
        <fui-form-item label="发行总量" prop="issueNumber" left="0" marginTop="14" :padding="['16rpx', 0]">
          <fui-input size="28" maxlength="9" :padding="[0]" :borderBottom="false" type="number" placeholder="所有用户可领取券的总数" :min="0" v-model="form.issueNumber" :disabled="disabledEdit" :color="formColor" @input="onChangeTotalNum">
            <fui-text text="张" size="24"></fui-text>
          </fui-input>
        </fui-form-item>
        <fui-form-item label="每家限额" prop="averageLimit" left="0" marginTop="14" :padding="['16rpx', 0]">
          <fui-input size="28" maxlength="9" :padding="[0]" :borderBottom="false" type="number" placeholder="每家限领的总数量" v-model="form.averageLimit" :disabled="disabledEdit" :color="formColor" @input="onChangePerNum">
            <fui-text text="张" size="24"></fui-text>
          </fui-input>
        </fui-form-item>
      </view>
      <!-- <view class="form-block">
        <fui-form-item label="优惠券说明" prop="description" left="0" marginTop="14" :padding="['16rpx', 0]">
          <template v-slot:vertical>
            <fui-textarea size="28" maxlength="200" height="64rpx" :isCounter="true" radius="16" borderColor="#DFDFDF" v-model="form.description" :disabled="disabledEdit" :color="formColor" placeholder="请输入优惠券说明" textareaBorder></fui-textarea>
          </template>
        </fui-form-item>
      </view> -->
    </fui-form>

    <view class="btn-wrapper ui-fixed-footer">
      <template v-if="!couponId">
        <fui-button class="ui-btn-primary_plain" text="取消" height="78rpx" radius="8rpx" :margin="['0', '54rpx', '0', '0']" @click="tab.navigateBack"></fui-button>
        <fui-button text="保存" height="78rpx" radius="8rpx" :margin="['0']" :disabled="isLoading" @click="handleSubmit"></fui-button>
      </template>
      <template v-else-if="disabledEdit">
        <fui-button text="修改" height="78rpx" radius="8rpx" :margin="['0', '54rpx', '0', '0']" :disabled="isLoading" @click="isEdit = true"></fui-button>
        <fui-button text="发布" height="78rpx" background="#3cdb9a" disabledBackground="#3cdb9a" radius="8rpx" :margin="['0']" :disabled="isLoading" @click="handlePublish"></fui-button>
      </template>
      <template v-else>
        <fui-button class="ui-btn-primary_plain" text="取消" height="78rpx" radius="8rpx" :margin="['0', '54rpx', '0', '0']" @click="handleCancel"></fui-button>
        <fui-button text="保存" height="78rpx" radius="8rpx" :margin="['0']" :disabled="isLoading" @click="handleSubmit"></fui-button>
      </template>
    </view>

    <!-- 时间 -->
    <fui-date-picker :show="onShowDatePicker" type="5" :value="defaultDateTime" @change="onChangeDate" @cancel="onCancelDate"></fui-date-picker>

    <!-- 选择运营品类 -->
    <multilevel-picker ref="categoryPickerRef" :maxLevel="1" :data="categoryData" :cacheData="categoryCacheData"
      @submit="submitCategory" :defaultProps="categoryProps"></multilevel-picker>
  </view>
</template>

<script setup>
import { ref, unref, computed, inject } from 'vue'
import { onLoad, onShow, onBackPress } from '@dcloudio/uni-app'
import { useStore } from 'vuex'
import utils from '@/components/firstui/fui-utils'
import { COUPON_USER_TYPE, COUPON_GOODS_RANGE } from './consts'
import pageHeader from '@/components/header'
import multilevelPicker from '@/components/multilevel'
import couponApi from '@/api/coupon'

const store = useStore()
const tab = inject('$tab')
const modal = inject('$modal')

const customTitle = ref('新增优惠券')
const couponId = ref('')
const isEdit = ref(false)
const disabledEdit = computed(() => !!couponId.value && !isEdit.value)
const formColor = computed(() => disabledEdit.value ? '#999' : '#333')
onLoad((option) => {
  categoryData.value = store.getters.productCategoryFormatting
  isEdit.value = false
  if (option.couponId) {
    customTitle.value = '待发布优惠券'
    couponId.value = option.couponId
    getCouponDetail()
  }
})

const formRef = ref(null)
const form = ref({
  targetCrowd: 21,
  productScope: store.getters.userType == 1 ? 31 : 71
})
const rules = [
  {
    name: 'name',
    rule: ['required'],
    msg: ['请输入优惠券名称']
  },
  {
    name: 'startReceiveTimeText',
    rule: ['required'],
    msg: ['请选择领取起始时间']
  },
  {
    name: 'endReceiveTimeText',
    rule: ['required'],
    msg: ['请选择领取截止时间']
  },
  {
    name: 'useStartTimeText',
    rule: ['required'],
    msg: ['请选择使用起始时间']
  },
  {
    name: 'useEndTimeText',
    rule: ['required'],
    msg: ['请选择使用截止时间']
  },
  {
    name: 'startNum',
    rule: ['required'],
    msg: ['优惠信息设置不完整，请检查']
  },
  {
    name: 'discountNum',
    rule: ['required'],
    msg: ['优惠信息设置不完整，请检查']
  },
  {
    name: 'issueNumber',
    rule: ['required'],
    msg: ['请输入发行总量']
  },
  {
    name: 'averageLimit',
    rule: ['required'],
    msg: ['请输入每家限额']
  }
]

const handleChangeUserType = (code) => {
  if (disabledEdit.value) return
  form.value.targetCrowd = code
}
const filterGoodsRange = computed(() => {
  let arr = []
  if (store.getters.userType == 1) {
    arr = Object.values(COUPON_GOODS_RANGE).splice(0, 3)
  } else {
    arr = Object.values(COUPON_GOODS_RANGE).splice(3, 5)
  }
  return arr
})
const handleChangeGoodsRange = (productScope) => {
  if (disabledEdit.value) return
  form.value.productScope = productScope
  checkedCategoryIds.value = []
  checkedSupplierIds.value = []
  checkedGoodsIds.value = []
  store.commit('SET_COUPON_SUPPLIER', [])
  store.commit('SET_COUPON_GOODS', [])
}

// 优惠时间
const defaultDateTime = utils.dateFormatter(new Date(), 'y-m-d h:i', 4)
const onShowDatePicker = ref(false)
const curDateFiled = ref('')
const handleShowDatePicker = (field) => {
  if (disabledEdit.value) return
  curDateFiled.value = field
  onShowDatePicker.value = true
}
const onChangeDate = (e) => {
  form.value[curDateFiled.value] = e ? `${e.year}/${e.month}/${e.day} ${e.hour}:${e.minute}` : ''
  onShowDatePicker.value = false
}
const onCancelDate = () => {
  onShowDatePicker.value = false
}

// 指定品类
const checkedCategoryIds = ref([])
const categoryData = ref([])
const categoryPickerRef = ref(null)
const categoryProps = {
	text: 'name',
	value: 'id',
	children: 'children'
}
const categoryCacheData = ref([])
const onShowCategoryPicker = () => {
	categoryPickerRef.value.show()
}
const submitCategory = (res) => {
  categoryCacheData.value = res.cacheData
  checkedCategoryIds.value = res.data.map(item => item.value)
}

// 指定供应商
const checkedSupplierIds = ref([])
const handleManageSullier = () => {
  tab.navigateTo(`/pages/coupon/selectSupplier?couponId=${couponId.value}&disabledEdit=${disabledEdit.value ? '1' : '0'}`)
}

// 指定商品
const checkedGoodsIds = ref([])
const handleManageGoods = () => {
  tab.navigateTo(`/pages/coupon/selectGoods?couponId=${couponId.value}&disabledEdit=${disabledEdit.value ? '1' : '0'}`)
}

onShow(() => {
  if (form.value.productScope == 33) {
    checkedSupplierIds.value = store.getters.couponSupplier
  }
  if (form.value.productScope == 72) {
    checkedGoodsIds.value = store.getters.couponGoods
  }
})

onBackPress(() => {
  store.commit('SET_COUPON_SUPPLIER', [])
  store.commit('SET_COUPON_GOODS', [])
})

// 优惠信息
const onChangeStartNum = async (value) => {
  if (value < 0) {
    modal.msgError('满减门槛必须大于等于0！')
    form.value.startNum = await ''
  } else if (value.toString().indexOf('.') > -1) {
    modal.msgError('满减门槛必须为整数！')
    form.value.startNum = await ''
  }
}
const onChangeDiscountNum = async (value) => {
  if (value <= 0) {
    modal.msgError('减免金额必须大于0！')
    form.value.discountNum = await ''
  } else if (value.toString().indexOf('.') > -1) {
    modal.msgError('减免金额必须为整数！')
    form.value.discountNum = await ''
  }
}

// 发行信息
const onChangeTotalNum = async (value) => {
  if (value <= 0) {
    modal.msgError('发行总量必须大于0！')
    form.value.issueNumber = await ''
  } else if (value.toString().indexOf('.') > -1) {
    modal.msgError('发行总量必须为整数！')
    form.value.issueNumber = await ''
  }
}
const onChangePerNum = async (value) => {
  if (value <= 0) {
    modal.msgError('每家限额必须大于0！')
    form.value.averageLimit = await ''
  } else if (value.toString().indexOf('.') > -1) {
    modal.msgError('每家限额必须为整数！')
    form.value.averageLimit = await ''
  }
}

// 活动详情
const getCouponDetail = () => {
  modal.loading('加载中...')
  try{
    couponApi.getCouponDetail(couponId.value).then(res => {
      modal.closeLoading()
      if (res.code === 0 && res.data) {
        form.value = res.data
        form.value.oldReceiveStartTime = form.value.receiveStartTime
        form.value.startReceiveTimeText = utils.dateFormatter(new Date(res.data.receiveStartTime), 'y/m/d h:i', 4)
        form.value.endReceiveTimeText = utils.dateFormatter(new Date(res.data.receiveEndTime), 'y/m/d h:i', 4)
        form.value.useStartTimeText = utils.dateFormatter(new Date(res.data.useStartTime), 'y/m/d h:i', 4)
        form.value.useEndTimeText = utils.dateFormatter(new Date(res.data.useEndTime), 'y/m/d h:i', 4)
        const resList = res.data.discountRules.split(',')
        form.value.startNum = resList[0].split('-')[0]
        form.value.discountNum = resList[0].split('-')[1]
        
        if (form.value.productScope == 32) { // 指定分类数据回显处理
          checkedCategoryIds.value = form.value.productScopeIds.split(',')
          categoryCacheData.value = categoryData.value.map(item => {
            return {
              checked: form.value.productScopeIds.indexOf(item.id) > -1,
              isActive: false,
              isShow: true,
              level: 1,
              parent: '00',
              parentArr: ['00'],
              status: form.value.productScopeIds.indexOf(item.id) > -1 ? 'all' : 'none',
              disabled: disabledEdit,
              text: item.name,
              value: item.id
            }
          })
        }

        if (form.value.productScope == 33) { // 指定供应商数据回显处理
          checkedSupplierIds.value = form.value.productScopeIds.split(',')
          store.commit('SET_COUPON_SUPPLIER', checkedSupplierIds.value)
        }

        if (form.value.productScope == 72) { // 指定商品数据回显处理
          checkedGoodsIds.value = form.value.productScopeIds.split(',')
          store.commit('SET_COUPON_GOODS', checkedGoodsIds.value)
        }
      } else {
        modal.msgError(res.msg)
      }
    })
  }catch(err){
    modal.closeLoading()
    modal.msgError(err)
  }
}

// 发布
const handlePublish = () => {
  modal.confirm(`确认发布优惠券"${form.value.name}"？`).then(() => {
    isLoading.value = true
    couponApi.updateCouponStatus({
      id: couponId.value,
      status: 12
    }).then((res) => {
      isLoading.value = false
      if (res.code === 0) {
        store.commit('SET_COUPON_SUPPLIER', [])
        store.commit('SET_COUPON_GOODS', [])
        modal.msg(`【${form.value.name}】已发布！`)
        setTimeout(() => {
          tab.navigateBack()
        }, 1000)
      } else {
        modal.msgError(res.msg || `【${form.value.name}】发布失败！`)
      }
    }).catch(err => {
      isLoading.value = false
      modal.msgError(err.msg || err || `【${form.value.name}】发布失败！`)
    })
  })
}

// 取消修改
const handleCancel = () => {
  isEdit.value = false
  getCouponDetail()
}

// 提交表单方法
const isLoading = ref(false)
const handleSubmit = async () => {
  const validRes = await formRef.value.validator(form.value, rules)
  if (!validRes.isPassed) {
    return
  }

  const receiveStartTime = new Date(form.value.startReceiveTimeText).getTime()
  const receiveEndTime = new Date(form.value.endReceiveTimeText).getTime()
  const useStartTime = new Date(form.value.useStartTimeText).getTime()
  const useEndTime = new Date(form.value.useEndTimeText).getTime()
  if (receiveEndTime <= receiveStartTime) {
    modal.msgError('领取截止时间必须大于领取起始时间！')
    return
  }
  if (useEndTime <= useStartTime) {
    modal.msgError('使用截止时间必须大于使用起始时间！')
    return
  }
  if (useStartTime <= receiveStartTime) {
    modal.msgError('使用开始时间必须大于领取起始时间！')
    return
  }
  if (receiveEndTime > useEndTime) {
    modal.msgError('领取截止时间必须小于等于使用截止时间！')
    return
  }

  if (form.value.startNum > 0 && form.value.discountNum - form.value.startNum >= 0) {
    modal.msgError('满减门槛大于0时，减免金额必须小于满减门槛！')
    return
  }
  if (form.value.issueNumber < form.value.averageLimit) {
    modal.msgError('每家限额必须小于等于发行总量！')
    return
  }
  let productScopeIds = []
  if (form.value.productScope == 32) {
    if (!checkedCategoryIds.value.length) {
      modal.msgError('请至少添加一个品类！')
      return
    }
    productScopeIds = checkedCategoryIds.value
  }
  if (form.value.productScope == 33) {
    if (!checkedSupplierIds.value.length) {
      modal.msgError('请至少添加一个供应商！')
      return
    }
    productScopeIds = checkedSupplierIds.value
  }
  if (form.value.productScope == 72) {
    if (!checkedGoodsIds.value.length) {
      modal.msgError('请至少添加一个商品！')
      return
    }
    productScopeIds = checkedGoodsIds.value
  }
  const formData = {
    id: couponId.value || '',
    name: form.value.name,
    useStartTime,
    useEndTime,
    receiveStartTime,
    receiveEndTime,
    description: '',
    targetCrowd: form.value.targetCrowd,
    discountRules: `${form.value.startNum}-${form.value.discountNum}`,
    issueNumber: form.value.issueNumber,
    averageLimit: form.value.averageLimit,
    productScope: form.value.productScope,
    productScopeIds: productScopeIds.join(',')
  }
  if (store.getters.userType != 1) {
    formData.supplierId = store.getters.companyId
  }
  const apiUrl = couponId.value ? 'updateCoupon' : 'addCoupon'
  isLoading.value = true
  couponApi[apiUrl](store.getters.userType, formData).then((res) => {
    isLoading.value = false
    if (res.code === 0) {
      store.commit('SET_COUPON_SUPPLIER', [])
      store.commit('SET_COUPON_GOODS', [])
      modal.msg(`优惠券信息已${couponId.value ? '修改' : '添加'}！`)
      setTimeout(() => {
        tab.navigateBack()
      }, 1000)
    } else {
      modal.msgError(res.msg)
    }
  }).catch(err => {
    isLoading.value = false
  })
}
</script>

<style lang="scss" scoped>
@import "@/static/scss/form.scss";

.page-coupon-form {
  padding-bottom: 150rpx;

  .discount-wrapper {
    display: flex;
    align-items: center;
    margin-top: 32rpx;
    padding: 10rpx;
    ::v-deep .fui-text__wrap {
      .fui-text__content {
        white-space: nowrap;
      }
    }
    .fui-form__item-wrap {
      width: auto;
      border-radius: 8rpx !important;
      background-color: #f7f7f7 !important;
      margin: 0 10rpx;
      padding: 0 16rpx;
    }
    .fui-icon {
      margin-left: 24rpx;
    }
  }
  ::v-deep.textarea-box .fui-form__wrap-inner {
    display: initial !important;
    padding: 0 !important;
  }

  .cycle-box {
    display: flex;
    align-items: center;
    margin-top: 20rpx;

    .cycle {
      width: 200rpx;
      height: 64rpx;
      background: #F5F7FE;
      border-radius: 0rpx 0rpx 0rpx 0rpx;
      opacity: 1;
      border: 2rpx solid #E7EBFB;
      font-size: 24rpx;
      font-family: PingFang SC, PingFang SC;
      font-weight: 400;
      color: #333333;
      text-align: center;
      line-height: 64rpx;
      margin-right: 20rpx;
      position: relative;
    }

    .cycle-active {
      font-weight: bold;
      color: var(--fui-color-primary);
      border: 2rpx solid var(--fui-color-primary);
    }

    .cycleimg {
      width: 30rpx;
      height: 27rpx;
      display: block;
      position: absolute;
      right: 0;
      bottom: 0;
    }
  }
}
</style>